
import socket
import subprocess
import struct
phone = socket.socket()

phone.bind(('127.0.0.1', 8888))

phone.listen(5)

# 4. 接收连接
print('start')
conn, addr = phone.accept()
while 1:
    try:
        cmd = conn.recv(1024)
        obj = subprocess.Popen(cmd.decode('utf-8'),
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               )

        result = obj.stdout.read() + obj.stderr.read()
        # print(f'服务端发送的总字节数{len(result)}')

        # 1. 制作报头
        total_size = len(result)

        # 2. 将不固定长度的int类型的报头,转化成固定长度bytes 4个字节
        # 将一个数字转化成等长度的bytes类型。
        total_size_bytes = struct.pack('i', total_size)

        # 3. 发送报头
        conn.send(total_size_bytes)

        # 4. 发送原数据
        conn.send(result)
    except ConnectionResetError:
        break
conn.close()
phone.close()




